package com.example.weather;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lecho.lib.hellocharts.view.LineChartView;

/**
 * Created by asd on 2016/9/14.
 */
public class Fragment2 extends Fragment implements View.OnClickListener {
    private View view;
    private ImageButton ivKindCity;
    private ImageButton ivReplace;
    private LineChartView lineChartView;
    private LineChartView lineChartView1;
    private String httpUrl = "http://apis.baidu.com/apistore/weatherservice/cityname";
    private String s = null;
    private List<Weather> forcastData;
    private List<Integer> num;
    private TextView tvTitle;
    private TextView bigWendu;
    private TextView tvType;
    private TextView tvFengxiang;
    private TextView tvFengli;
    private TextView tvTodayheightemp;
    private TextView tvTodaylowtemp;
    private TextView tvTomheightemp;
    private TextView tvTomlowtemp;
    private TextView tvAfterheigitemp;
    private TextView tvAfterlowtemp;
    private TextView Date0;
    private TextView Date1;
    private TextView Day2;
    private TextView Date2;
    private TextView Day3;
    private TextView Date3;
    private TextView Day4;
    private TextView Date4;
    private TextView Day5;
    private TextView Date5;
    private TextView Type0;
    private TextView Type1;
    private TextView Type2;
    private TextView Type3;
    private TextView Type4;
    private TextView Type5;
    private TextView fengxiang0;
    private TextView fengli0;
    private TextView fengxiang1;
    private TextView fengli1;
    private TextView fengxiang2;
    private TextView fengli2;
    private TextView fengxiang3;
    private TextView fengli3;
    private TextView fengxiang4;
    private TextView fengli4;
    private TextView fengxiang5;
    private TextView fengli5;
    private TextView tttvvv;
    private ImageView iv0;
    private ImageView iv1;
    private ImageView iv2;
    private ImageView iv3;
    private ImageView iv4;
    private ImageView iv5;
    List<Map<String, Integer>> aa = null;
    List<ImageView> imagePic = null;
    private String[] cityName = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {

                    String s = aMapLocation.getProvince();
                    cityName = s.split("市");
                    init();
                    getHelloCharts();


//可在其中解析amapLocation获取相应内容。
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main, null);

        getCityName();
        return view;
    }

    private void init() {
        forcastData = new ArrayList<>();
        ivKindCity = (ImageButton) view.findViewById(R.id.ib_kindCity);
        ivReplace = (ImageButton) view.findViewById(R.id.replace);
        tvTitle = (TextView) view.findViewById(R.id.tv_Title);
        bigWendu = (TextView) view.findViewById(R.id.bigWendu);
        tvType = (TextView) view.findViewById(R.id.tv_type);
        tvFengxiang = (TextView) view.findViewById(R.id.tv_fengxiang);
        tvFengli = (TextView) view.findViewById(R.id.tv_fengli);

        tttvvv = (TextView) view.findViewById(R.id.tttvvv);
        tvTodayheightemp = (TextView) view.findViewById(R.id.tv_todayheightemp);
        tvTodaylowtemp = (TextView) view.findViewById(R.id.tv_todaylowtemp);
        tvTomheightemp = (TextView) view.findViewById(R.id.tv_tomheightemp);
        tvTomlowtemp = (TextView) view.findViewById(R.id.tv_tomlowtemp);
        tvAfterheigitemp = (TextView) view.findViewById(R.id.tv_afterheigitemp);
        tvAfterlowtemp = (TextView) view.findViewById(R.id.tv_afterlowtemp);

        Date0 = (TextView) view.findViewById(R.id.Date0);
        Date1 = (TextView) view.findViewById(R.id.Date1);
        Day2 = (TextView) view.findViewById(R.id.Day2);
        Date2 = (TextView) view.findViewById(R.id.Date2);
        Day3 = (TextView) view.findViewById(R.id.Day3);
        Date3 = (TextView) view.findViewById(R.id.Date3);
        Day4 = (TextView) view.findViewById(R.id.Day4);
        Date4 = (TextView) view.findViewById(R.id.Date4);
        Day5 = (TextView) view.findViewById(R.id.Day5);
        Date5 = (TextView) view.findViewById(R.id.Date5);

        Type0 = (TextView) view.findViewById(R.id.Type0);
        Type1 = (TextView) view.findViewById(R.id.Type1);
        Type2 = (TextView) view.findViewById(R.id.Type2);
        Type3 = (TextView) view.findViewById(R.id.Type3);
        Type4 = (TextView) view.findViewById(R.id.Type4);
        Type5 = (TextView) view.findViewById(R.id.Type5);

        iv0 = (ImageView) view.findViewById(R.id.iv0);
        iv1 = (ImageView) view.findViewById(R.id.iv1);
        iv2 = (ImageView) view.findViewById(R.id.iv2);
        iv3 = (ImageView) view.findViewById(R.id.iv3);
        iv4 = (ImageView) view.findViewById(R.id.iv4);
        iv5 = (ImageView) view.findViewById(R.id.iv5);

        fengxiang0 = (TextView) view.findViewById(R.id.fengxiang0);
        fengli0 = (TextView) view.findViewById(R.id.fengli0);
        fengxiang1 = (TextView) view.findViewById(R.id.fengxiang1);
        fengli1 = (TextView) view.findViewById(R.id.fengli1);
        fengxiang2 = (TextView) view.findViewById(R.id.fengxiang2);
        fengli2 = (TextView) view.findViewById(R.id.fengli2);
        fengxiang3 = (TextView) view.findViewById(R.id.fengxiang3);
        fengli3 = (TextView) view.findViewById(R.id.fengli3);
        fengxiang4 = (TextView) view.findViewById(R.id.fengxiang4);
        fengli4 = (TextView) view.findViewById(R.id.fengli4);
        fengxiang5 = (TextView) view.findViewById(R.id.fengxiang5);
        fengli5 = (TextView) view.findViewById(R.id.fengli5);
        ivKindCity.setOnClickListener(this);
        ivReplace.setOnClickListener(this);
        getWeather();
    }

    private void getWeather() {
        httpUrl = "http://apis.baidu.com/apistore/weatherservice/recentweathers" + "?cityname=" + cityName[0].toString();
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addHeader("apikey", "6d96b140df1db1b19388daeaec241d05");
        utils.send(HttpRequest.HttpMethod.GET, httpUrl, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                s = responseInfo.result;
                getText(s);
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.v("msg", "解析失败");
            }
        });
    }

    private void getText(String str) {
        try {
            //解析本天天气
            JSONObject jsonObject = new JSONObject(str);
            JSONObject jsonData = jsonObject.getJSONObject("retData");

            String city = jsonData.getString("city");
            tvTitle.setText(city);
            JSONObject jsonToday = jsonData.getJSONObject("today");
            String date = jsonToday.getString("date");
            String week = jsonToday.getString("week");
            //平均温度

            String curTmp = jsonToday.getString("curTemp");
            bigWendu.setText(curTmp);
            String fengxiang = jsonToday.getString("fengxiang");
            tvFengxiang.setText(fengxiang);
            String fengli = jsonToday.getString("fengli");
            tvFengli.setText(fengli);
            //最高温度
            String highttemp = jsonToday.getString("hightemp");
            tvTodayheightemp.setText(highttemp);
            //最低温度
            String lowtemp = jsonToday.getString("lowtemp");
            tvTodaylowtemp.setText(lowtemp);
            //天气状况：例多云
            String type = jsonToday.getString("type");
            try {
                setMessage(curTmp, type);
            } catch (Exception e) {
                e.printStackTrace();
            }
            tvType.setText(type);
            JSONArray jsonForcast = jsonData.getJSONArray("forecast");
            JSONArray jsonHistory = jsonData.getJSONArray("history");
            JSONArray js = jsonToday.getJSONArray("index");
            JSONObject jsToday = (JSONObject) js.get(0);
            tttvvv.setText(jsToday.getString("details"));
            //解析前一天天气
            JSONObject isonDay = (JSONObject) jsonHistory.get(jsonHistory.length() - 1);
            getDay(isonDay);
            Weather weather1 = new Weather();
            weather1.setDate(date);
            weather1.setWeek(week);
            weather1.setFengxiang(fengxiang);
            weather1.setFengli(fengli);
            weather1.setHightemp(highttemp);
            weather1.setLowtemp(lowtemp);
            weather1.setType(type);
            forcastData.add(weather1);
//解析未来四天的天气
            num = new ArrayList<>();
            getData(jsonForcast);

            //把带℃的String数据转换成Int类型的数据
            for (int i = 0; i < forcastData.size(); i++) {
                getNum(forcastData.get(i).getHightemp());

            }
            tvTomheightemp.setText(forcastData.get(1).getHightemp());
            tvTomlowtemp.setText(forcastData.get(1).getLowtemp());
            tvAfterheigitemp.setText(forcastData.get(2).getHightemp());
            tvAfterlowtemp.setText(forcastData.get(2).getLowtemp());
            //实现折线图数据填充
            new CHelloChart(lineChartView, num, Color.RED);

            num = new ArrayList<>();
            for (int i = 0; i < forcastData.size(); i++) {
                getNum(forcastData.get(i).getLowtemp());
            }
            //实现折线图数据填充
            new CHelloChart(lineChartView1, num, Color.BLUE);
            Date0.setText(forcastData.get(0).getDate());
            Type0.setText(forcastData.get(0).getType());
            fengxiang0.setText(forcastData.get(0).getFengxiang());
            fengli0.setText(forcastData.get(0).getFengli());
            Date1.setText(forcastData.get(1).getDate());
            Type1.setText(forcastData.get(1).getType());
            fengxiang1.setText(forcastData.get(1).getFengxiang());
            fengli1.setText(forcastData.get(1).getFengli());
            Date2.setText(forcastData.get(2).getDate());
            Type2.setText(forcastData.get(2).getType());
            fengxiang2.setText(forcastData.get(2).getFengxiang());
            fengli2.setText(forcastData.get(2).getFengli());
            Day2.setText(forcastData.get(2).getWeek());
            Date3.setText(forcastData.get(3).getDate());
            Type3.setText(forcastData.get(3).getType());
            fengxiang3.setText(forcastData.get(3).getFengxiang());
            fengli3.setText(forcastData.get(3).getFengli());
            Day3.setText(forcastData.get(3).getWeek());
            Date4.setText(forcastData.get(4).getDate());
            Type4.setText(forcastData.get(4).getType());
            fengxiang4.setText(forcastData.get(4).getFengxiang());
            fengli4.setText(forcastData.get(4).getFengli());
            Day4.setText(forcastData.get(4).getWeek());
            Date5.setText(forcastData.get(5).getDate());
            Type5.setText(forcastData.get(5).getType());
            fengxiang5.setText(forcastData.get(5).getFengxiang());
            fengli5.setText(forcastData.get(5).getFengli());
            Day5.setText(forcastData.get(5).getWeek());
            getPic();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getData(JSONArray jsp) {
        for (int i = 0; i < jsp.length(); i++) {
            Weather weather = new Weather();
            JSONObject js = null;
            try {
                js = (JSONObject) jsp.get(i);
                weather.setDate(js.getString("date"));
                weather.setWeek(js.getString("week"));
                weather.setFengxiang(js.getString("fengxiang"));
                weather.setFengli(js.getString("fengli"));
                weather.setHightemp(js.getString("hightemp"));
                weather.setLowtemp(js.getString("lowtemp"));
                weather.setType(js.getString("type"));
                forcastData.add(weather);
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
    }

    private void getDay(JSONObject jsss) {
        Weather weather = new Weather();
        try {
            weather.setDate(jsss.getString("date"));
            weather.setWeek(jsss.getString("week"));
            weather.setFengxiang(jsss.getString("fengxiang"));
            weather.setFengli(jsss.getString("fengli"));
            weather.setHightemp(jsss.getString("hightemp"));
            weather.setLowtemp(jsss.getString("lowtemp"));
            weather.setType(jsss.getString("type"));
            forcastData.add(weather);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void getCityName() {
        mLocationClient = new AMapLocationClient(getActivity());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(1000000);

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();

    }

    private void getNum(String str) {
        String a[] = str.split("℃");
        num.add(Integer.parseInt(a[0]));
    }

    String[] type = {"多云", "晴"};
    int[] typePic = {R.mipmap.w1, R.mipmap.w0};

    private void getPic() {
        aa = new ArrayList<>();
        Map<String, Integer> map = new HashMap();
        for (int a = 0; a < type.length; a++) {

            map.put(type[a], typePic[a]);

        }

        imagePic = new ArrayList<>();
        imagePic.add(iv0);
        imagePic.add(iv1);
        imagePic.add(iv2);
        imagePic.add(iv3);
        imagePic.add(iv4);
        imagePic.add(iv5);
        for (int i = 0; i < forcastData.size(); i++) {
            for (int j = 0; j < type.length; j++) {
                if (type[j].equals(forcastData.get(i).getType())) {
                    imagePic.get(i).setImageResource(map.get(type[j]));
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_kindCity:
                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                dialog.setTitle("请输入城市名称");
                final EditText txt = new EditText(getActivity());
                dialog.setView(txt);
                dialog.setNegativeButton("取消", null);
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        cityName[0] = txt.getText().toString();
                        init();
                        getHelloCharts();
                    }
                }).show();
                break;
            case R.id.replace:
                init();
                getHelloCharts();
                break;
        }
    }

    private void getHelloCharts() {
        lineChartView = (LineChartView) view.findViewById(R.id.linechart);
        lineChartView1 = (LineChartView) view.findViewById(R.id.linechart1);

    }

    //设置不能被clean的通知栏
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setMessage(String wenDu, String type) throws Exception {
        NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
//新建一个Notification管理器;
//API level 11
        Notification.Builder builder = new Notification.Builder(getActivity());//新建Notification.Builder对象
        PendingIntent intent = PendingIntent.getActivity(getActivity(), 0, new Intent(getActivity(), Welcome.class), 0);
//PendingIntent点击通知后所跳转的页面
        builder.setContentTitle(wenDu);
        builder.setContentText(type);
        builder.setSmallIcon(R.mipmap.abnormal_heating);
        builder.setContentIntent(intent);//执行intent
        Notification notification = builder.getNotification();//将builder对象转换为普通的notification
        notification.flags = Notification.FLAG_NO_CLEAR;//让通知栏不可被clean
        manager.notify(1, notification);//运行notification
    }
}
